'use strict'
const express = require('express')
const http = require('http')
const router = express.Router()
const jwt = require('jsonwebtoken')
const secret = 'my_token' // 密钥

// 主服务有token,但session中没有,传过来token,对其进行授权(验证Token)
router.post('/api/auth/author', (req, res) => {
  // 验证 Token
  jwt.verify(req.body.token, secret, (error, decoded) => {
    if (error) {
      console.log(error.message, '验证未通过')
      return
    }
    // 验证通过
    console.log(decoded, '验证通过')
    res.send(decoded)
  })
})

// 登录接口+校验成功后生成Token
router.post('/api/auth/login', (req, res) => {
  const loginRes = res
  console.log(req.body, 'req.body')
  console.log(req.body.redirectPath, 'redirectPath')
  // 向用户管理系统进行验证(待添加)
  console.log(req.body, 'req.body')
  let user = {
    name: req.body.name,
    password: req.body.password
  }
  console.log(user, 'user')
  const postData = JSON.stringify(user)
  console.log(postData, 'postData')
  const options = {
    path: '/api/user/testUser',
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Content-Length': Buffer.byteLength(postData)
    }
  }
  const request = http.request(options, (res) => {
    res.setEncoding('utf8')
    res.on('data', (chunk) => {
      const userInfo = JSON.parse(chunk)
      console.log(userInfo, 'chunk')
      if (userInfo.code) {
        console.log(userInfo.info)
        // 用户管理验证通过后进行Token生成
        // 签发 Token
        const token = jwt.sign(userInfo.info, secret, { expiresIn: 60 * 60 })
        console.log(token, 'token')
        // 存入cookie
        loginRes.cookie('token', token)
        // 重定向到target(待添加)
        if (req.body.redirectPath) {
          console.log('有target')
          const path = req.body.redirectPath.split('=')[1]
          console.log(path, 'target')
          // loginRes.header('Location', '/home')
          // loginRes.setHeader('Location', 'http://www.baidu.com');
          
          // loginRes.location('/home')
          // loginRes.end()
          // loginRes.redirect('http://www.baidu.com')
        } else {
          console.log('无target')
        }
        // 输出签发的 Token
        loginRes.send({
          code: 1,
          token: token,
          message: '校验用户成功'
        })
      } else {
        console.log(userInfo.info)
        loginRes.send({
          code: 0,
          message: '无此用户'
        })
      }
    })
    res.on('end', () => {
      console.log('响应中已无数据。')
    })
  })
  request.on('error', (e) => {
    console.error(`请求遇到问题: ${e.message}`)
  })
  // 写入数据到请求主体
  request.write(postData)
  request.end()
  // loginRes.send('User verification failed,Not signed')
})

module.exports = router
